package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ")
    public void orderStatusTask() {
        log.info("定时处理超时订单+{}", LocalTime.now());
        //select * from  where status = 0 and order_time+15min < now time
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endTime = now.minusMinutes(15);
        List<Orders> list = orderMapper.findByStatusAndTime(Orders.PENDING_PAYMENT, endTime);
        if (list != null && list.size() > 0) {
            list.forEach(l -> {
                l.setStatus(Orders.CANCELLED);
                l.setCancelReason("超时支付");
                l.setCancelTime(LocalDateTime.now());
                orderMapper.update(l);
            });
        }
    }

    /**
     * 处理一直派送中定单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void orderConTask() {
        log.info("处理派送定单");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endtime = now.minusMinutes(61);
        List<Orders> list = orderMapper.findByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, endtime);
        if (list != null && list.size() > 0) {
            list.forEach(l -> {
                l.setStatus(Orders.COMPLETED);
                l.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(l);
            });
        }
    }
}
